import { Bubble,PhotoSwipe } from 'weaver-mobile';
import { getLabel,showConfirm } from './common';
import * as EmSDK from './emSDK';
import {signImgResize} from './SignUtil';
import { _,GlobalUtil } from './pcPublic';
import jQuery from 'jquery';
import base from "./base";
//图片懒加载
window.formImgLazyLoad = function(container){
	if(!!!container || container.length === 0)
		return;
	// 获取父元素的高度
	var contHeight = container.outerHeight();
	var contWidth = container.outerWidth();
	// 获取父元素相对于文档页顶部的距离，这边要注意了，分为以下两种情况；
	if (container.get(0) === window) {
		// 第一种情况父元素为window，获取浏览器滚动条已滚动的距离；$(window)没有offset()方法；
		var contop = jQuery(window).scrollTop();
		var conleft = jQuery(window).scrollLeft();
	} else {
		// 第二种情况父元素为非window元素，获取它的滚动条滚动的距离；
		var contop = container.offset().top;
		var conleft = container.offset().left;
	}
	
	container.find("img[original-src]").each(function(){
		//对象顶部与文档顶部之间的距离，如果它小于父元素底部与文档顶部的距离，则说明垂直方向上已经进入可视区域了；
		//console.log("jQuery(this).offset().top--",jQuery(this).offset().top,"contop--",contop,"contHeight--",contHeight)
		var post = jQuery(this).offset().top - (contop + contHeight);
		//对象底部与文档顶部之间的距离，如果它大于父元素顶部与文档顶部的距离，则说明垂直方向上已经进入可视区域了；
		var posb = jQuery(this).offset().top + jQuery(this).height() - contop;
		// 水平方向上同理；
		var posl = jQuery(this).offset().left - (conleft + contWidth);
		var posr = jQuery(this).offset().left + jQuery(this).width() - conleft;

		//console.log("jQuery(this).is(':visible')",jQuery(this).is(':visible'),"post--",post,"posb--",posb,"posl--",posl,"posr--",posr);
		if ((post < 0 && posb > 0) && (posl < 0 && posr > 0)) {
			var originalSrc = jQuery(this).attr("original-src");
			if (originalSrc != "") {
				let style = (jQuery(this).attr("original-style") || "") + "max-width:100%";
				jQuery(this).removeAttr("style").attr("style", style).removeAttr("original-style");
				jQuery(this).attr("width", jQuery(this).attr("original-width")).removeAttr("original-width");
				jQuery(this).attr("height", jQuery(this).attr("original-height")).removeAttr("original-height");
				var imgKey = jQuery(this).attr('img-key');
                const _vthis = jQuery(this);
				if(imgKey == 'signlist' || _vthis.hasClass("signatureImg")) {} else {
                    window.setTimeout(function(){
                        window.adjustImgWidth(_vthis);
                    },100);
				}
				jQuery(this).removeAttr("src").attr("src", originalSrc).removeAttr("original-src");
				if(jQuery(this).hasClass("handWrittenSign")){
					GlobalUtil.handWritingHander(this);
				}
			}
		}
	});
}

//处理图片宽度自适应
window.adjustImgWidth = function(vthis){
	// const wrapWidth = window.innerWidth;
	// const imgWidth = vthis.width();
	// if (imgWidth >= wrapWidth) {
	// 	vthis.width("100%").removeAttr("height").css("height", "");
	// }
	vthis.css("max-width","100%").removeAttr("height").css("height", "");
	//绑定图片预览事件
	vthis.addClass("formImgPlay");
	vthis.bind("click", function(){
		window.preViewImg(vthis);
	});
}

window.preViewImg = function(arg, imgOrigin){
	if(typeof arg === "object"){
		const { propFileCfg = {} } = base.wfLayoutStore;
		const { handwriting_download_switch = "0" } = propFileCfg;
		let handwritingPre = handwriting_download_switch == 1 && arg.attr("name") == "handWrittenSign";
		if(handwritingPre || arg.hasClass("signatureImg")) return;
	}
	const current = typeof arg === "object" ? arg.attr("src") : arg;
	const urls = getFormAllImages(imgOrigin);
	if(EmSDK.judgeApiSupport("previewImage")){
		EmSDK.preViewImage({urls, current});
	}else{
		const curindex = _.indexOf(urls, current)
		const imageArr = urls.map(url => {
			return {url: url}
		});
		PhotoSwipe.showImage(imageArr, curindex);
	}
}

//获取表单中所有图片对象的src地址，包含富文本、签字意见、附件上传、图片上传字段等等
const getFormAllImages = (imgOrigin) =>{
  const { propFileCfg = {} } = base.wfLayoutStore;
  const { handwriting_download_switch = "0" } = propFileCfg;
  let urls = [];
  let obj = [];
  if(imgOrigin == 'isFormCommunicate') {
    obj = 	jQuery(".communicateImgPlay");
  } else {
	  if(window.location.hash.includes("#/req/editDetailRow")){
		obj = 	jQuery(".wf-editrow .formImgPlay")
	  }else{
		obj = 	jQuery(".formImgPlay")
	  }
  }
	obj.each(function(){
		const vthis = jQuery(this);
		let handwritingPre = handwriting_download_switch == 1 && jQuery(this).attr("name") == "handWrittenSign";
		if(vthis.is("img") && !handwritingPre && !jQuery(this).hasClass("signatureImg")){
			urls.push(vthis.attr("src"));		//图片元素
		}else{
			if(!!vthis.attr("data-imgsrc")){
				let fileimgsrc = vthis.attr("data-imgsrc");
				//fileimgsrc = fileimgsrc.replace("&download=1", "");
				urls.push(fileimgsrc);	//附件上传中图片
			}
		}
	});
	return urls;
}

window.scrollEndEvent = function(dom, event,offset){
	const offsetHeight = dom.offsetHeight;
	const scrollTop = dom.scrollTop;
	const scrollHeight = dom.scrollHeight;
	if(scrollHeight - scrollTop - offsetHeight <= offset + 1){
		event();
	}
}

//系统提醒工作流需要相关JS
const errorNoticeUtil = {
	showCondition: function(conditid){
		jQuery('#'+conditid).toggle();
	},
	handleResetBtn: function(){
		const url = jQuery('#wfSErrorResetBtn').attr('href');
		const title = jQuery('#wfSErrorResetBtn').attr('title');
		const type = jQuery('#wfSErrorResetBtn').attr('type');
		jQuery('#wfSErrorResetBtn').attr('href','javascript:void(0)').removeAttr('target').removeAttr('title');
		jQuery('#wfSErrorResetBtn').attr('onclick',"errorNoticeUtil.resetWorkflowCfg('"+url+"','"+title+"','"+type+"')");
		jQuery("#wfSErrorResetBtn").removeAttr('style');
	},
	resetWorkflowCfg: function(url,title,type){
		showConfirm({title: "移动端暂不支持路径设置，请登录PC端调整设置！"}, false);
	},
	triggerSystemWorkflow: function(prefix, url, title, loginuserid, type){
		const globalStore = window.WfForm.getGlobalStore();
		const { requestid,belongTest } = globalStore.commonParam;
		prefix = prefix.replace(/~0~/g, "<span class='importantInfo'>");
		prefix = prefix.replace(/~1~/g, "</span>");
		prefix = prefix.replace(/~2~/g, "<span class='importantDetailInfo'>");
		let infohtml = jQuery('.wf-error-msg-detail').html();
		if(!infohtml) {
			infohtml = "";
		} else {
			infohtml = "<div class='wf-error-msg-detail'>" + infohtml + "</div>";
		}
		const botfix = type == "3" ? getLabel(18913,"流程干预") : getLabel(126558,"进行设置");
		const messagedetail = `${infohtml}<span>${prefix}，请<a id="wfSErrorResetBtn" href="${url}" title="${title}" type="${type}"> 点击这里 </a>${botfix}</span>`;
		jQuery.ajax({
			type: 'post',
			url: '/workflow/request/TriggerRemindWorkflow.jsp?_' + new Date().getTime() + "=1",
			data: {
				remark: messagedetail,
				loginuserid: loginuserid,
				requestid: requestid
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				Bubble.error(getLabel(22397,'发送失败'), 2);
			},
			success: function(data, textStatus) {
				Bubble.success(getLabel(516558,'已成功向提醒人发送提醒流程'), 2);
			}
		});
	}
}
window.errorNoticeUtil = errorNoticeUtil;
//生成系统提醒流程
window.triggerSystemWorkflow = errorNoticeUtil.triggerSystemWorkflow;

//Iframe区域相关方法
window.iframeOperate = (function(){

	function showIframeArea(vthis){
		jQuery(vthis).closest("td").find(".iframeLoading").hide();
		jQuery(vthis).show();
	}

	//Iframe区域高度自适应高度
	function autoAdjustHeight(vthis){
		var iframeObj = jQuery(vthis);
		var funObj = function(){autoAdjustHeight(vthis)};
		var eachcount = parseInt(iframeObj.attr("eachcount"));
		if(eachcount > 10){
			iframeObj.css("height", "100px");
			return;
		}
		var contextObj = iframeObj[0].contentWindow.document;
		var bodyContentHeight = contextObj.body.scrollHeight;
		//if(window.console) console.log("scrollHeight:"+bodyContentHeight+"  |offsetHeight:"+contextObj.body.offsetHeight)
		if(bodyContentHeight == 0){
			iframeObj.attr("eachcount", eachcount+1);
			window.setTimeout(funObj, 500);
		}else{
			iframeObj.css("height", bodyContentHeight+"px");
		}
	}

	return{
		//Iframe区域onload事件
		loadingOver: function(vthis){
			if(jQuery(vthis).attr("adjustheight") == "y"){
				window.setTimeout(function(){
					showIframeArea(vthis);
					autoAdjustHeight(vthis);
				},800);
			}else{
				showIframeArea(vthis);
			}
		}
	}
})();

//二维码、条形码相关方法
window.scancodeOperate = (function(){

	function adjustSize_scancode(vthis){
		try{
			var parentHeight = vthis.closest("td").height();
			var curHeight = vthis.height();
			//if(window.console)console.log("二维码/条形码宽度调整:"+parentHeight+"  |  "+curHeight);
			if(parseInt(parentHeight)-parseInt(curHeight) > 8)		//td高度会包含图片高度及上边框高度，避免死循环触发
				vthis.css("height", parentHeight);
		}catch(e){}
	}

	return {
		//ready触发自适应单元格大小（针对所在行存在高度渐变时，故绑定个resize）
		readyAdjustSize: function(obj){
			var vthis = jQuery(obj);
			vthis.resize(function(){
				adjustSize_scancode(vthis);
			});
			adjustSize_scancode(vthis);
		}
	}
})();
